package org.yocastlong.mybatisplus.db.handle;

import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.SM4;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;
import org.yocastlong.mybatisplus.db.encryption.Sm4CacheKey;
import org.yocastlong.mybatisplus.db.encryption.Sm4Manager;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author 朱海龙
 * 2025/6/7 8:35
 */
public class FiledSm4EncryptHandle implements TypeHandler<String> {

    private SM4 sm4;

    public FiledSm4EncryptHandle() {
        final String sm4Key = "SukKDtIUIqhmHtx1R2hZyw==";
        final String sm4IV = "lesV7dctrcHNc3Ct1NxryQ==";
        final Mode mode = Mode.CBC;
        final Padding padding = Padding.PKCS5Padding;
        Sm4CacheKey sm4CacheKey = new Sm4CacheKey();
        sm4CacheKey.setIv(sm4IV);
        sm4CacheKey.setKey(sm4Key);
        sm4CacheKey.setMode(mode);
        sm4CacheKey.setPadding(padding);
        sm4 = Sm4Manager.getSm4Instance(sm4CacheKey);
    }

    @Override
    public void setParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
        if (StringUtils.isBlank(parameter)) {
            ps.setString(i, parameter);
            return;
        }
        try {
            String newParameter = sm4.encryptBase64(parameter);
            ps.setString(i, newParameter);
        } catch (Exception e) {
            ps.setString(i, parameter);
        }
    }

    @Override
    public String getResult(ResultSet rs, String columnName) throws SQLException {
        String filed = rs.getString(columnName);
        return decodeFiled(filed);
    }

    @Override
    public String getResult(ResultSet rs, int columnIndex) throws SQLException {
        String filed = rs.getString(columnIndex);
        return decodeFiled(filed);
    }

    @Override
    public String getResult(CallableStatement cs, int columnIndex) throws SQLException {
        String filed = cs.getString(columnIndex);
        return decodeFiled(filed);
    }

    private String decodeFiled(String filed) {
        if (StringUtils.isBlank(filed)) {
            return filed;
        }
        try {
            return sm4.decryptStr(filed);
        } catch (Exception e) {
            return filed;
        }
    }

}
